home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1997 May: Tool Chest / Dev.CD May 97 TC.toast / Sample Code / Snippets / Toolbox / Password / Source / Sample.c < prev   
Encoding:
C/C++ Source or Header  |  1996-09-17  |  24.9 KB  |  706 lines  |  [TEXT/CWIE]

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    This is just a hacked version of CSample.  Ignore any bits referring to the
  4. #    traffic lights, etc.
  5. #
  6. #    9/13/96 PG brought code into 20th century.
  7. #
  8. ------------------------------------------------------------------------------*/
  9.  
  10.  
  11. #include <Types.h>
  12. #include <Resources.h>
  13. #include <QuickDraw.h>
  14. #include <Fonts.h>
  15. #include <Events.h>
  16. #include <Windows.h>
  17. #include <Menus.h>
  18. #include <TextEdit.h>
  19. #include <Dialogs.h>
  20. #include <Desk.h>
  21. #include <ToolUtils.h>
  22. #include <Memory.h>
  23. #include <SegLoad.h>
  24. #include <Files.h>
  25. #include <OSUtils.h>
  26. #include <OSEvents.h>
  27. #include <DiskInit.h>
  28. #include <Packages.h>
  29. #include <Traps.h>
  30. #include <Limits.h>
  31. #include <Processes.h>
  32. #include "Sample.h"        /* bring in all the #defines for Sample */
  33.  
  34. #include "Password.h"
  35.  
  36. /* The "g" prefix is used to emphasize that a variable is global. */
  37.  
  38. /* GMac is used to hold the result of a SysEnvirons call. This makes
  39.    it convenient for any routine to check the environment. */
  40. SysEnvRec    gMac;                /* set up by Initialize */
  41.  
  42. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  43.    trap is available. If it is false, we know that we must call GetNextEvent. */
  44. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  45.  
  46. /* GInBackground is maintained by our osEvent handling routines. Any part of
  47.    the program can check it to find out if it is currently in the background. */
  48. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  49.  
  50.  
  51. /* The following globals are the state of the window. If we supported more than
  52.    one window, they would be attatched to each document, rather than globals. */
  53.  
  54. /* Define HiWrd and LoWrd macros for efficiency. */
  55. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  56. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  57.  
  58. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  59.    dependency on the ordering of fields within a Rect */
  60. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  61. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  62.  
  63. #ifdef applec
  64.     /* This routine is part of the MPW runtime library. This external
  65.            reference to it is done so that we can unload its segment, %A5Init. */
  66.  
  67.     extern void _DataInit();
  68. #endif
  69.  
  70. /*    Display an alert that tells the user an error occurred, then exit the program.
  71.     This routine is used as an ultimate bail-out for serious errors that prohibit
  72.     the continuation of the application. Errors that do not require the termination
  73.     of the application should be handled in a different manner. Error checking and
  74.     reporting has a place even in the simplest application. The error number is used
  75.     to index an 'STR#' resource so that a relevant message can be displayed. */
  76.  
  77. #pragma segment Main
  78. static void AlertUser(void)
  79. {
  80.     short        itemHit;
  81.  
  82.     SetCursor(&qd.arrow);
  83.     itemHit = Alert(rUserAlert, nil);
  84.     ExitToShell();
  85. } /* AlertUser */
  86.  
  87. /*    Check to see if a given trap is implemented. This is only used by the
  88.     Initialize routine in this program, so we put it in the Initialize segment.
  89.     The recommended approach to see if a trap is implemented is to see if
  90.     the address of the trap routine is the same as the address of the
  91.     Unimplemented trap. */
  92. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  93.     if a ToolTrap is out of range of a pre-MacII ROM. */
  94.  
  95. #pragma segment Initialize
  96. // check to see if a given trap is implemented. We follow IM VI-3-8.
  97.  
  98. static Boolean TrapAvailable(short theTrap)
  99. {
  100.     TrapType theTrapType;
  101.     short numToolboxTraps;
  102.     
  103.     if ((theTrap & 0x0800) > 0)
  104.         theTrapType = ToolTrap;
  105.     else
  106.         theTrapType = OSTrap;
  107.  
  108.     if (theTrapType == ToolTrap)
  109.     {
  110.         theTrap = theTrap & 0x07ff;
  111.         if (NGetTrapAddress(_InitGraf, ToolTrap) == NGetTrapAddress(0xaa6e, ToolTrap))
  112.             numToolboxTraps = 0x0200;
  113.         else
  114.             numToolboxTraps = 0x0400;
  115.         if (theTrap >= numToolboxTraps)
  116.             theTrap = _Unimplemented;
  117.     };
  118.  
  119.     return (NGetTrapAddress(theTrap, theTrapType) != NGetTrapAddress(_Unimplemented, ToolTrap));
  120. }
  121.  
  122. /*    Set up the whole world, including global variables, Toolbox managers,
  123.     and menus. We also create our one application window at this time.
  124.     Since window storage is non-relocateable, how and when to allocate space
  125.     for windows is very important so that heap fragmentation does not occur.
  126.     Because Sample has only one window and it is only disposed when the application
  127.     quits, we will allocate its space here, before anything that might be a locked
  128.     relocatable object gets into the heap. This way, we can force the storage to be
  129.     in the lowest memory available in the heap. Window storage can differ widely
  130.     amongst applications depending on how many windows are created and disposed. */
  131.  
  132. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  133.     this module. If an error is detected, instead of merely doing an ExitToShell,
  134.     which leaves the user without much to go on, we call AlertUser, which puts
  135.     up a simple alert that just says an error occurred and then calls ExitToShell.
  136.     Since there is no other cleanup needed at this point if an error is detected,
  137.     this form of error- handling is acceptable. If more sophisticated error recovery
  138.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  139.  
  140. #pragma segment Initialize
  141. static void Initialize (void)
  142. {    Handle        menuBar;
  143.     long        total, contig;
  144.     EventRecord event;
  145.     short        count;
  146.  
  147.     gInBackground = false;
  148.  
  149.     InitGraf((Ptr) &qd.thePort);
  150.     InitFonts();
  151.     InitWindows();
  152.     InitMenus();
  153.     TEInit();
  154.     InitDialogs(nil);
  155.     InitCursor();
  156.     
  157.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  158.          if you are using it. */
  159.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  160.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  161.         of checking for port availability themselves. */
  162.     
  163.     /*    This next bit of code is necessary to allow the default button of our
  164.         alert be outlined.
  165.         1.02 - Changed to call EventAvail so that we don't lose some important
  166.         events. */
  167.      
  168.     for (count = 1; count <= 3; count++)
  169.         EventAvail(everyEvent, &event);
  170.     
  171.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  172.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  173.         call to SysEnvirons by calling it after initializing AppleTalk. */
  174.      
  175.     SysEnvirons(kSysEnvironsVersion, &gMac);
  176.     
  177.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  178.     
  179.     if (gMac.machineType < 0) AlertUser();
  180.     
  181.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  182.         in TrapAvailable if a tool trap value is out of range. */
  183.         
  184.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent);
  185.  
  186.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  187.         ApplicationZone, and StackSpace and comparing that to the minimum size we told
  188.         MultiFinder we needed. This did not work well because it assumed too much about
  189.         the relationship between what we asked MultiFinder for and what we would actually
  190.         get back, as well as how to measure it. Instead, we will use an alternate
  191.         method comprised of two steps. */
  192.      
  193.     /*    It is better to first check the size of the application heap against a value
  194.         that you have determined is the smallest heap the application can reasonably
  195.         work in. This number should be derived by examining the size of the heap that
  196.         is actually provided by MultiFinder when the minimum size requested is used.
  197.         The derivation of the minimum size requested from MultiFinder is described
  198.         in Sample.h. The check should be made because the preferred size can end up
  199.         being set smaller than the minimum size by the user. This extra check acts to
  200.         insure that your application is starting from a solid memory foundation. */
  201.      
  202.     if ((long) GetApplLimit() - (long) ApplicationZone() < kMinHeap) AlertUser();
  203.     
  204.     /*    Next, make sure that enough memory is free for your application to run. It
  205.         is possible for a situation to arise where the heap may have been of required
  206.         size, but a large scrap was loaded which left too little memory. To check for
  207.         this, call PurgeSpace and compare the result with a value that you have determined
  208.         is the minimum amount of free memory your application needs at initialization.
  209.         This number can be derived several different ways. One way that is fairly
  210.         straightforward is to run the application in the minimum size configuration
  211.         as described previously. Call PurgeSpace at initialization and examine the value
  212.         returned. However, you should make sure that this result is not being modified
  213.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  214.         PurgeSpace. Make sure to remove that call before shipping, though. */
  215.     
  216.     /* ZeroScrap(); */
  217.  
  218.     PurgeSpace(&total, &contig);
  219.     if (total < kMinSpace) AlertUser();
  220.  
  221.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  222.         to check memory is that we can now give the user an alert to tell him/her what
  223.         happened. Although it is possible that the memory situation could be worsened by
  224.         displaying an alert, MultiFinder would gracefully exit the application with
  225.         an informative alert if memory became critical. Here we are acting more
  226.         in a preventative manner to avoid future disaster from low-memory problems. */
  227.  
  228.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  229.     if ( menuBar == nil ) AlertUser();
  230.     SetMenuBar(menuBar);                    /* install menus */
  231.     DisposeHandle(menuBar);
  232.     AppendResMenu(GetMenuHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  233.     DrawMenuBar();
  234.     
  235. } /*Initialize*/
  236.  
  237. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  238.     it will return either a pending event or a null event. In either case,
  239.     the where field of the event record will contain the current position
  240.     of the mouse in global coordinates and the modifiers field will reflect
  241.     the current state of the modifiers. Another way to get the global
  242.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  243.     being sure that thePort is set to a valid port. */
  244.  
  245. #pragma segment Main
  246. static void GetGlobalMouse (Point *mouse)
  247. {
  248.     EventRecord    event;
  249.     
  250.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  251.     *mouse = event.where;                /* just the mouse position */
  252. } /*GetGlobalMouse*/
  253.  
  254. /* Check to see if a window belongs to a desk accessory. */
  255.  
  256. #pragma segment Main
  257. static Boolean IsDAWindow (WindowPtr    window)
  258. {
  259.     if ( window == nil )
  260.         return false;
  261.     else    /* DA windows have negative windowKinds */
  262.         return ( ((WindowPeek) window)->windowKind < 0 );
  263. } /*IsDAWindow*/
  264.  
  265. /*    Check to see if a window belongs to the application. If the window pointer
  266.     passed was NIL, then it could not be an application window. WindowKinds
  267.     that are negative belong to the system and windowKinds less than userKind
  268.     are reserved by Apple except for windowKinds equal to dialogKind, which
  269.     mean it is a dialog.
  270.     1.02 - In order to reduce the chance of accidentally treating some window
  271.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  272.     is userKind. If you add different kinds of windows to Sample you'll need
  273.     to change how this all works. */
  274.  
  275. #pragma segment Main
  276. static Boolean IsAppWindow (WindowPtr    window)
  277. {
  278.     short        windowKind;
  279.  
  280.     if ( window == nil )
  281.         return false;
  282.     else {    /* application windows have windowKinds = userKind (8) */
  283.         windowKind = ((WindowPeek) window)->windowKind;
  284.         return ( windowKind == userKind );
  285.     }
  286. } /*IsAppWindow*/
  287.  
  288. /*    Change the cursor's shape, depending on its position. This also calculates the region
  289.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  290.     that region, an event would be generated, causing this routine to be called,
  291.     allowing us to change the region to the region the mouse is currently in. If
  292.     there is more to the event than just “the mouse moved”, we get called before the
  293.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  294.     this is called again before we     fall back into WNE. */
  295.  
  296. #pragma segment Main
  297. static void AdjustCursor(Point mouse, RgnHandle region)
  298. {
  299.     WindowPtr    window;
  300.     RgnHandle    arrowRgn;
  301.     RgnHandle    plusRgn;
  302.     Rect        globalPortRect;
  303.  
  304.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  305.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  306.         /* calculate regions for different cursor shapes */
  307.         arrowRgn = NewRgn();
  308.         plusRgn = NewRgn();
  309.  
  310.         /* start with a big, big rectangular region */
  311.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  312.  
  313.         /* calculate plusRgn */
  314.         if ( IsAppWindow(window) ) {
  315.             SetPort(window);    /* make a global version of the viewRect */
  316.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  317.             globalPortRect = window->portRect;
  318.             RectRgn(plusRgn, &globalPortRect);
  319.             SectRgn(plusRgn, window->visRgn, plusRgn);
  320.             SetOrigin(0, 0);
  321.         }
  322.  
  323.         /* subtract other regions from arrowRgn */
  324.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  325.  
  326.         /* change the cursor and the region parameter */
  327.         if ( PtInRgn(mouse, plusRgn) ) {
  328.             SetCursor(*GetCursor(plusCursor));
  329.             CopyRgn(plusRgn, region);
  330.         } else {
  331.             SetCursor(&qd.arrow);
  332.             CopyRgn(arrowRgn, region);
  333.         }
  334.  
  335.         /* get rid of our local regions */
  336.         DisposeRgn(arrowRgn);
  337.         DisposeRgn(plusRgn);
  338.     }
  339. } /*AdjustCursor*/
  340.  
  341. /*    Enable and disable menus based on the current state.
  342.     The user can only select enabled menu items. We set up all the menu items
  343.     before calling MenuSelect or MenuKey, since these are the only times that
  344.     a menu item can be selected. Note that MenuSelect is also the only time
  345.     the user will see menu items. This approach to deciding what enable/
  346.     disable state a menu item has the advantage of concentrating all
  347.     the decision-making in one routine, as opposed to being spread throughout
  348.     the application. Other application designs may take a different approach
  349.     that is just as valid. */
  350.  
  351. #pragma segment Main
  352. static void AdjustMenus (void)
  353. {
  354.     WindowPtr    window;
  355.     MenuHandle    menu;
  356.  
  357.     window = FrontWindow();
  358.  
  359.     menu = GetMenuHandle(mFile);
  360.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  361.         EnableItem(menu, iClose);
  362.     else
  363.         DisableItem(menu, iClose);    /* but not our traffic light window */
  364.  
  365.     menu = GetMenuHandle(mEdit);
  366.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  367.         EnableItem(menu, iUndo);
  368.         EnableItem(menu, iCut);
  369.         EnableItem(menu, iCopy);
  370.         EnableItem(menu, iClear);
  371.         EnableItem(menu, iPaste);
  372.     } else {                        /* …but we don’t use it */
  373.         DisableItem(menu, iUndo);
  374.         DisableItem(menu, iCut);
  375.         DisableItem(menu, iCopy);
  376.         DisableItem(menu, iClear);
  377.         DisableItem(menu, iPaste);
  378.     }
  379.     
  380.     menu = GetMenuHandle(mPassword);
  381.         EnableItem(menu, iTwoItem);
  382.         EnableItem(menu, iDifferentFont);
  383.         EnableItem(menu, iInternalBuffer);
  384.     
  385. } /*AdjustMenus*/
  386.  
  387. /* Close a window. This handles desk accessory and application windows. */
  388.  
  389. /*    1.01 - At this point, if there was a document associated with a
  390.     window, you could do any document saving processing if it is 'dirty'.
  391.     DoCloseWindow would return true if the window actually closed, i.e.,
  392.     the user didn’t cancel from a save dialog. This result is handy when
  393.     the user quits an application, but then cancels the save of a document
  394.     associated with a window. */
  395.  
  396. #pragma segment Main
  397. static Boolean DoCloseWindow (WindowPtr    window)
  398. {
  399.     if ( IsDAWindow(window) )
  400.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  401.     else if ( IsAppWindow(window) )
  402.         CloseWindow(window);
  403.     return true;
  404. } /*DoCloseWindow*/
  405.  
  406. /* Clean up the application and exit. We close all of the windows so that
  407.  they can update their documents, if any. */
  408.  
  409. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  410.     shell, but will return instead. */
  411.  
  412. #pragma segment Main
  413. static void Terminate (void)
  414. {
  415.     WindowPtr    aWindow;
  416.     Boolean        closed;
  417.     
  418.     closed = true;
  419.     do {
  420.         aWindow = FrontWindow();                /* get the current front window */
  421.         if (aWindow != nil)
  422.             closed = DoCloseWindow(aWindow);    /* close this window */    
  423.     }
  424.     while (closed && (aWindow != nil));
  425.     if (closed)
  426.         ExitToShell();                            /* exit if no cancellation */
  427. } /*Terminate*/
  428.  
  429. /*    This is called when an item is chosen from the menu bar (after calling
  430.     MenuSelect or MenuKey). It performs the right operation for each command.
  431.     It is good to have both the result of MenuSelect and MenuKey go to
  432.     one routine like this to keep everything organized. */
  433.  
  434. #pragma segment Main
  435. static void DoMenuCommand (long menuResult)
  436. {
  437.     short        menuID;                /* the resource ID of the selected menu */
  438.     short        menuItem;            /* the item number of the selected menu */
  439.     short        itemHit;
  440.     Str255        daName;
  441.     short        daRefNum;
  442.     Boolean        handledByDA;
  443.     Str255        password;
  444.  
  445.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  446.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  447.     switch ( menuID ) {
  448.         case mApple:
  449.             switch ( menuItem ) {
  450.                 case iAbout:        /* bring up alert for About */
  451.                     itemHit = Alert(rAboutAlert, nil);
  452.                     break;
  453.                 default:            /* all non-About items in this menu are DAs */
  454.                     /* type Str255 is an array in MPW 3 */
  455.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  456.                     daRefNum = OpenDeskAcc(daName);
  457.                     break;
  458.             }
  459.             break;
  460.         case mFile:
  461.             switch ( menuItem ) {
  462.                 case iClose:
  463.                     DoCloseWindow(FrontWindow());
  464.                     break;
  465.                 case iQuit:
  466.                     Terminate();
  467.                     break;
  468.             }
  469.             break;
  470.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  471.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  472.             break;
  473.         case mPassword:
  474.             switch ( menuItem ) {
  475.                 case iTwoItem:
  476.                     TwoItemDialog(password);
  477.                     break;
  478.                 case iDifferentFont:
  479.                     DifferentFontDialog(password);
  480.                     break;
  481.                 case iInternalBuffer:
  482.                     InternalBufferDialog(password);
  483.                     break;
  484.             }
  485.             DisplayPassword(password);
  486.             break;
  487.     }
  488.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  489. } /*DoMenuCommand*/
  490.  
  491. /*    This is called when a mouse-down event occurs in the content of a window.
  492.     Other applications might want to call FindControl, TEClick, etc., to
  493.     further process the click. */
  494.  
  495. #pragma segment Main
  496. static void DoContentClick(WindowPtr    window)
  497. {
  498. #pragma unused (window)
  499. } /*DoContentClick*/
  500.  
  501. /*    This is called when a window is activated or deactivated.
  502.     In Sample, the Window Manager's handling of activate and
  503.     deactivate events is sufficient. Other applications may have
  504.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  505.  
  506. #pragma segment Main
  507. static void DoActivate(WindowPtr window, Boolean becomingActive)
  508. {
  509.     if ( IsAppWindow(window) ) {
  510.         if ( becomingActive )
  511.             /* do whatever you need to at activation */ ;
  512.         else
  513.             /* do whatever you need to at deactivation */ ;
  514.     }
  515. } /*DoActivate*/
  516.  
  517. /* Draw the contents of the application window. We do some drawing in color, using
  518.    Classic QuickDraw's color capabilities. This will be black and white on old
  519.    machines, but color on color machines. At this point, the window’s visRgn
  520.    is set to allow drawing only where it needs to be done. */
  521.  
  522. #pragma segment Main
  523. static void DrawWindow(WindowPtr    window)
  524. {
  525.     SetPort(window);
  526.  
  527.     EraseRect(&window->portRect);    /* clear out any garbage that may linger */
  528. } /*DrawWindow*/
  529.  
  530. /*    This is called when an update event is received for a window.
  531.     It calls DrawWindow to draw the contents of an application window.
  532.     As an efficiency measure that does not have to be followed, it
  533.     calls the drawing routine only if the visRgn is non-empty. This
  534.     will handle situations where calculations for drawing or drawing
  535.     itself is very time-consuming. */
  536.  
  537. #pragma segment Main
  538. static void DoUpdate(WindowPtr    window)
  539. {
  540.     if ( IsAppWindow(window) ) {
  541.         BeginUpdate(window);                /* this sets up the visRgn */
  542.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  543.             DrawWindow(window);
  544.         EndUpdate(window);
  545.     }
  546. } /*DoUpdate*/
  547.  
  548. /* Do the right thing for an event. Determine what kind of event it is, and call
  549.  the appropriate routines. */
  550.  
  551. #pragma segment Main
  552. static void DoEvent (EventRecord    *event)
  553. {
  554.     short        part, err;
  555.     WindowPtr    window;
  556.     Boolean        hit;
  557.     char        key;
  558.     Point        aPoint;
  559.  
  560.     switch ( event->what ) {
  561.         case mouseDown:
  562.             part = FindWindow(event->where, &window);
  563.             switch ( part ) {
  564.                 case inMenuBar:                /* process a mouse menu command (if any) */
  565.                     AdjustMenus();
  566.                     DoMenuCommand(MenuSelect(event->where));
  567.                     break;
  568.                 case inSysWindow:            /* let the system handle the mouseDown */
  569.                     SystemClick(event, window);
  570.                     break;
  571.                 case inContent:
  572.                     if ( window != FrontWindow() ) {
  573.                         SelectWindow(window);
  574.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  575.                     } else
  576.                         DoContentClick(window);
  577.                     break;
  578.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  579.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  580.                     break;
  581.                 case inGrow:
  582.                     break;
  583.                 case inZoomIn:
  584.                 case inZoomOut:
  585.                     hit = TrackBox(window, event->where, part);
  586.                     if ( hit ) {
  587.                         SetPort(window);                /* the window must be the current port... */
  588.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  589.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  590.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  591.                     }
  592.                     break;
  593.             }
  594.             break;
  595.         case keyDown:
  596.         case autoKey:                        /* check for menukey equivalents */
  597.             key = event->message & charCodeMask;
  598.             if ( event->modifiers & cmdKey )            /* Command key down */
  599.                 if ( event->what == keyDown ) {
  600.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  601.                     DoMenuCommand(MenuKey(key));
  602.                 }
  603.             break;
  604.         case activateEvt:
  605.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  606.             break;
  607.         case updateEvt:
  608.             DoUpdate((WindowPtr) event->message);
  609.             break;
  610.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  611.             to a diskEvt, so that the user can format a floppy. */
  612.         case diskEvt:
  613.             if ( HiWord(event->message) != noErr ) {
  614.                 SetPt(&aPoint, kDILeft, kDITop);
  615.                 err = DIBadMount(aPoint, event->message);
  616.             }
  617.             break;
  618.         case kOSEvent:
  619.         {
  620.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  621.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  622.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  623.                     gInBackground = (event->message & kResumeMask) == 0;
  624.                     DoActivate(FrontWindow(), !gInBackground);
  625.                     break;
  626.             }
  627.             break;
  628.         }    
  629.     }
  630. } /*DoEvent*/
  631.  
  632. /*    Get events forever, and handle them by calling DoEvent.
  633.     Get the events by calling WaitNextEvent, if it's available, otherwise
  634.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  635.  
  636. #pragma segment Main
  637. static void EventLoop(void)
  638. {
  639.     RgnHandle    cursorRgn;
  640.     Boolean        gotEvent;
  641.     EventRecord    event;
  642.     Point        mouse;
  643.  
  644.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  645.     do {
  646.         /* use WNE if it is available */
  647.         if ( gHasWaitNextEvent ) {
  648.             GetGlobalMouse(&mouse);
  649.             AdjustCursor(mouse, cursorRgn);
  650.             gotEvent = WaitNextEvent(everyEvent, &event, LONG_MAX, cursorRgn);
  651.         }
  652.         else {
  653.             SystemTask();
  654.             gotEvent = GetNextEvent(everyEvent, &event);
  655.         }
  656.         if ( gotEvent ) {
  657.             /* make sure we have the right cursor before handling the event */
  658.             AdjustCursor(event.where, cursorRgn);
  659.             DoEvent(&event);
  660.         }
  661.         /*    If you are using modeless dialogs that have editText items,
  662.             you will want to call IsDialogEvent to give the caret a chance
  663.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  664.             for a non-NIL value before calling IsDialogEvent. */
  665.     } while ( true );    /* loop forever; we quit via ExitToShell */
  666. } /*EventLoop*/
  667.  
  668. #pragma segment Main
  669. void main(void)
  670. {
  671.     #ifdef applec
  672.         UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  673.     #endif
  674.     
  675.     /* 1.01 - call to ForceEnvirons removed */
  676.     
  677.     /*    If you have stack requirements that differ from the default,
  678.         then you could use SetApplLimit to increase StackSpace at 
  679.         this point, before calling MaxApplZone. */
  680.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  681.  
  682.     Initialize();                    /* initialize the program */
  683.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  684.  
  685.     EventLoop();                    /* call the main event loop */
  686. }
  687.  
  688. /**************************************************************************************
  689. *** 1.01 DoCloseBehind(window) was removed ***
  690.  
  691.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  692.     and not having to worry about updating the windows, but it suffered
  693.     from a fatal flaw. If a desk accessory owned two windows, it would
  694.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  695.     got around to calling DoCloseWindow for that other window that was already
  696.     closed, things would go very poorly. Another option would be to have a
  697.     procedure, GetRearWindow, that would go through the window list and return
  698.     the last window. Instead, we decided to present the standard approach
  699.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  700.     has a potential benefit in that the window whose document needs to be saved
  701.     may be visible since it is the front window, therefore decreasing the
  702.     chance of user confusion. For aesthetic reasons, the windows in the
  703.     application should be checked for updates periodically and have the
  704.     updates serviced.
  705. **************************************************************************************/
  706.